<?php
/*
 * @Author: zeyudada
 * @Date: 2022-01-09 19:43:28
 * @LastEditTime: 2022-03-17 09:20:55
 * @Description: 用户端AJAX接口
 * @Q Q: zeyunb@vip.qq.com(1776299529)
 * @E-mail: admin@zeyudada.cn
 * 
 * Copyright (c) 2022 by zeyudada, All Rights Reserved. 
 */

include("../include/common.php");
$act = isset($_GET['act']) ? $_GET['act'] : null;
@header('Content-Type: application/json; charset=UTF-8');

switch ($act) {
    case 'login':
        //登录
        if (empty($_POST['name']) || empty($_POST['pass']) || empty($_POST['code'])) json(['code' => "201", 'msg' => '请填好所有字段！']);
        if (strtoupper($_POST['code']) != $_SESSION['code']) {
            unset($_SESSION['code']);
            json(['code' => "201", 'msg' => '验证码错误']);
        }
        $pwd = md5($_POST['pass']);
        $row = $DB->get_row("SELECT * FROM `user` WHERE `name` = '{$_POST['name']}'");

        if (empty($row)) json(['code' => 201, 'msg' => '账号不存在！']);
        if ($row['name'] == $_POST['name'] && $row['password'] == $pwd) {
            $_SESSION['user'] = $row;

            $DB->query("INSERT INTO `log`(`userid`, `msg`, `ip`, `time`) VALUES ({$row['id']}, '用户" . $_POST['name'] . "成功登录用户后台', '" . getip() . "', '" . date('Y-m-d H:i:s') . "')");

            json(['code' => 200, 'msg' => '登陆成功']);
        } else {
            json(['code' => 201, 'msg' => '账号或密码错误']);
        }
        break;

    case 'profile':
        //修改用户资料
        //UPDATE `zeyudada`.`user` SET `gender` = '男', `birthday` = '2006-04-02', `tel` = 18888888888, `mail` = 'admin@zeyudada.cn', `qq` = 123456, `wechat` = 'zeyudada', `address` = 'zeyudada' WHERE `id` = 1
        if ($DB->query("UPDATE `user` SET `gender` = '{$_POST['gender']}', `birthday` = '{$_POST['birthday']}', `tel` = {$_POST['tel']}, `mail` = '{$_POST['mail']}', `qq` = {$_POST['qq']}, `wechat` = '{$_POST['wechat']}', `address` = '{$_POST['address']}' WHERE `id` = " . $_SESSION['user']['id']) > 0) json(['code' => 200, 'msg' => '修改成功']);
        else json(['code' => 201, 'msg' => '修改失败']);
        break;

    case 'passwd':
        if (empty($_POST['old']) || empty($_POST['new'])) json(['code' => "201", 'msg' => '请填好所有字段！']);

        $old = md5($_POST['old']);
        $pwd = md5($_POST['new']);
        $row = $DB->get_row("SELECT * FROM `user` WHERE `id` = " . $_SESSION['user']['id']);

        if ($row['password'] == $old) {
            $DB->query("UPDATE `user` SET `password` = '{$pwd}' WHERE `id` = " . $_SESSION['user']['id']);

            json(['code' => 200, 'msg' => '修改成功，新密码：' . $_POST['new']]);
        } else {
            json(['code' => 201, 'msg' => '老密码错误']);
        }
        break;

    case 'exam':
        # 测试题目

        $ask = $DB->get_row("SELECT * FROM question ORDER BY RAND() LIMIT 1");

        json(['code' => 200, 'msg' => '获取数据成功！', 'data' => $ask]);
        break;

    case 'startans':
        # 开始答题
        if (empty($_GET['sort']) || !is_numeric($_GET['sort'])) json(['code' => "201", 'msg' => '请选择分类！']);

        $ask = $DB->getAll("SELECT * FROM `question` WHERE sort = ".intval($_GET['sort'])." ORDER BY RAND() limit 20");
        $count = count($ask);
        $_SESSION['count'] = $count;

        json(['code' => 200, 'msg' => '获取数据成功！', 'count' => $count, 'data' => $ask]);
        break;


    case 'postque':
        # 提交题目

        if(empty($_POST)||empty($_SESSION['count'])) json(['code' => "201", 'msg' => '请填好所有字段！']);
        if (empty($_POST['sort']) || !is_numeric($_POST['sort'])) json(['code' => "201", 'msg' => '请选择分类！']);

        $asks = $DB->getAll("SELECT * FROM `question` WHERE sort = ".intval($_POST['sort']));
        # 把所有项的键值改成id，方便比对
        foreach ($asks as $ask) {
            $question[$ask['id']] = $ask;
        }
        unset($asks);
        // 节省内存啦

        $correct = 0;

        foreach ($_POST as $key => $value) {
            if($question[$key]['answer'] == $value) $correct++;
        }

        $save = json_encode($_POST);
        $date = date('Y-m-d H-i-s');
        if ($DB->query("INSERT INTO `answer`(`userid`, `answer`, `time`, `date`, `correct`) VALUES ({$_SESSION['user']['id']}, '{$save}', '{$_POST['time']}', '{$date}', '{$correct}')") > 0) json(['code' => 200, 'msg' => '提交成功', 'correct' => $correct]);
        else json(['code' => 201, 'msg' => '提交失败，请尝试重新提交']);

        break;

    case 'getanswer':
        # 获取用户自己的回答

        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $users = $DB->getAll("SELECT * FROM `answer` WHERE `userid` = {$_SESSION['user']['id']} limit {$start},".intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `answer` WHERE `userid` = {$_SESSION['user']['id']}");
        if(!is_array($users)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $users]);
        break;
        

    case 'getlog':
        # 获取登录记录
        
        $page = $_GET['page'] - 1;
        $start = $page * $_GET['limit'];
        # 分页
        $logs = $DB->getAll("SELECT * FROM `log` WHERE `userid` = {$_SESSION['user']['id']} limit ".$start.",".intval($_GET['limit']));
        $count = $DB->get_row("SELECT count(*) FROM `log` WHERE `userid` = {$_SESSION['user']['id']}");
        if(!is_array($logs)) json(['code' => 203, 'msg' => '获取数据失败！']);
        json(['code' => 0, 'msg' => '获取数据成功！', 'count' => intval(end($count)), 'data' => $logs]);
        break;


    default:
        json(['code' => 500, 'msg' => '方法不存在！']);
        break;
}
